<?php
include('includes/stemmer.php');
include('class/class_connect.php');
include('class/abstract/class_paginator.php');
require_once('includes/rubriks.php');
include('class/class_checkGetData.php');
$aCheck=new checkGetData('f');
foreach($_GET as $key=>$vol)
{
	$_GET[$key]=$aCheck->safetyCheck($vol);
}
$search=$_GET['search'];
$aCheck->checkCity($_GET['city']);
$search=$_GET['search'];//iconv("UTF-8", "WINDOWS-1251", $_POST['search']);
$lsearch=mb_strtolower($search);
$searchWordArray=explode(' ', $search);
//echo $search.' -$search<br />';
$result=array();
$aStemmer=new Lingua_Stem_Ru();

$stopWords=array(
'и', 'И', 'или', 'Или', 'как', 'Как', 'Купить', 'купить', 'найти', 'куплю', 'а', 'А', 'у', 'У', 'в', 'В', 'на', 'На', 'с', 'С', 'По', 'по', '', ' ', '  ', '   '
);
function getRelevantRes($row, $searchWord, $stSearchWord)
{
	$row=mb_strtolower($row);
	$relevance=60;
	//if(strripos($row, substr($searchWord, 1))==1)$relevance=8;
	if(strripos($row, $searchWord)===0)$relevance=50;
	if(strripos($row, $stSearchWord)===0)$relevance=55;
	if(strripos($row, $stSearchWord)>0)$relevance=55;
	return($relevance);
}
function getRelevance($search, $searchRelevance, $searchEC, $row, $relevance, $entrWeigh)
{
	//echo $relevance;
	$aStemmer=new Lingua_Stem_Ru();
	$lsearch=mb_strtolower($search);
	$lrow=mb_strtolower($row);
	if($lrow==$lsearch)
		{
			$relevance=40;
		}
		if($i==1)$relevance+=1;
		if($i>1)$relevance+=2;
		//echo '!'.$relevance.','.$searchRelevance.'!';
		if($relevance<$searchRelevance)$searchRelevance=$relevance;
		//$searchRelevance=$relevance;
        $rowWords=explode(' ', $lrow);
        $searchWords=explode(' ', $lsearch);
        $entranceCoef=array();
        for($j=0; $j<count($rowWords); $j++)
        {
        	for($n=0; $n<count($searchWords); $n++)
        	{
        		$rowWord=$rowWords[$j];
        		$sWord=$aStemmer->stem_word($searchWords[$n]);
        		//echo '!'.$sWord.$rowWord.'!';
        		if(strripos($rowWord, $sWord)===0 or strripos($rowWord, $sWord)>0)$entranceCoef[]=1;
        	}
        }
        $entranceCoef=count($entranceCoef);
        $searchEC+=$entranceCoef;//+$entrWeigh;
        $relevance-=($entranceCoef*3);
        $relRes['EC']=$searchEC;
        $relRes['relevance']=$relevance;
        $relRes['searchRelevance']=$searchRelevance;
        return($relRes);
}
$ready=array();
$prNameready=array();
$prBrendready=array();
$prModelready=array();
$Mallready=array();
$prTready=array();
$divready=array();
$subdready=array();
//if($search[0]='')$search=substr($search, 1);
//if($search[strlen($search)-1]='')$search=substr($search, 0, strlen($search)-2);
for($i=0; $i<count($searchWordArray); $i++)
{
	$searchWord=mb_strtolower($searchWordArray[$i]);

	//echo '"'.$searchWord.'"';
	if(in_array($searchWord, $stopWords))continue;
	$stSearch=$aStemmer->stem_word($searchWord);
   	if($_GET['obj']=='firms')
   	{
   		$aConnect=new connect('f');
		$res=$aConnect->select_all($_GET['city'], "WHERE name LIKE '%".$stSearch."%' or short LIKE '%".$stSearch."%' or subdiv LIKE '%".$stSearch."%' or division LIKE '%".$stSearch."%'");
		while($row=mysql_fetch_array($res))
		{
			$relevance;
			$firmRelevance;
			$firmEC=array();
			$relevance=getRelevantRes($row['name'], $searchWord, $stSearch);
			$relRes=getRelevance($search, 60, 0, $row['name'], $relevance, 3);
			$searchRelevance=$relRes['searchRelevance'];
			$ec=$relRes['EC'];
			$relevance=$relRes['relevance'];
			$relevance=getRelevantRes($row['short'], $searchWord, $stSearch);
			$relRes=getRelevance($search, $searchRelevance, $ec, $row['short'], $relevance, 2);
			$searchRelevance=$relRes['searchRelevance'];
			$ec=$relRes['EC'];
			$relevance=$relRes['relevance'];
			$relevance=getRelevantRes($row['division'], $searchWord, $stSearch);
			$relRes=getRelevance($search, $searchRelevance, $ec, $row['division'], $relevance, 1);
			$searchRelevance=$relRes['searchRelevance'];
			$ec=$relRes['EC'];
			$relevance=$relRes['relevance'];
			$relevance=getRelevantRes($row['subdiv'], $searchWord, $stSearch);
			$relRes=getRelevance($search, $searchRelevance, $ec, $row['subdiv'], $relevance, 1);
			$searchRelevance=$relRes['searchRelevance'];
			$ec=$relRes['EC'];
			$relevance=$relRes['relevance'];
			$relevance=$searchRelevance-($ec*2);
			if(!in_array($row['name'], $ready))
		    {
				$result['obj'][$relevance][]='firms^'.$row['id'].'^'.$row['name'].'^'.$row['short'];
			    $ready[]=$row['name'];
			}
		}
		$aConnect=new connect('m');
		$res=$aConnect->select_all($_GET['city'], "WHERE name LIKE '%".$stSearch."%' or short LIKE '%".$stSearch."%'");
		while($row=mysql_fetch_array($res))
		{
			$relevance;
			$relevance=getRelevantRes($row['name'], $searchWord, $stSearch);
			$relRes=getRelevance($search, 60, 0, $row['name'], $relevance, 3);
			$searchRelevance=$relRes['searchRelevance'];
			$ec=$relRes['EC'];
			$relevance=$relRes['relevance'];
			$relevance=getRelevantRes($row['short'], $searchWord, $stSearch);
			$relRes=getRelevance($search, $searchRelevance, $ec, $row['short'], $relevance, 3);
			$searchRelevance=$relRes['searchRelevance'];
			$ec=$relRes['EC'];
			$relevance=$relRes['relevance'];

	        $relevance-=($ec*2);
			if(!in_array($row['short'], $Mallready))
		    {
				$result['obj'][$relevance][]='malls^'.$row['id'].'^'.$row['name'].'^'.$row['short'];
			    $Mallready[]=$row['short'];
			}
		}
    	continue;
   	}
   	if($_GET['obj']=='division')
   	{
	    foreach($divises as $division=>$vol)
	    {
	    	$ldivision=mb_strtolower($division);
	    	$relevance=getRelevantRes($ldivision, $searchWord, $stSearch);
	    	if($lsearch==$ldivision)
	    		$relevance=40;
	    	if($relevance<60)
	    	{
		    	$rowWords=explode(' ', $ldivision);
		        $searchWords=explode(' ', $lsearch);
		        $entranceCoef=array();
		        for($j=0; $j<count($rowWords); $j++)
		        {
		        	for($n=0; $n<count($searchWords); $n++)
		        	{
		        		$rowWord=$rowWords[$j];
		        		$sWord=$aStemmer->stem_word($searchWords[$n]);
		        		if(strripos($rowWord, substr($sWord, 1)))$entranceCoef[]=1;
		        	}
		        }
		        $entranceCoef=count($entranceCoef);
		        $relevance-=($entranceCoef*2);
		        //echo $relevance;
		        if(!in_array($division, $divready))
		        {
		    		$result['division'][$relevance][]=$division;
		    		$divready[]=$division;
		   		}

	    	}
	    	for($v=0; $v<count($vol); $v++)
	    	{
	    		$subdiv=$vol[$v];
	    		$lsubdiv=mb_strtolower($subdiv);
	    		$relevance=getRelevantRes($lsubdiv, $searchWord, $stSearch);
	    		if($lsearch==$lsubdiv)
	    			$relevance=40;
	    		if($relevance<60)
	    		{
		    		$entranceCoef=array();
		    		$rowWords=explode(' ', $lsubdiv);
			        for($j=0; $j<count($rowWords); $j++)
			        {
			        	for($n=0; $n<count($searchWords); $n++)
			        	{
			        		$rowWord=$rowWords[$j];
			        		$sWord=$aStemmer->stem_word($searchWords[$n]);
			        		if(strripos($rowWord, substr($sWord, 1)))$entranceCoef[]=1;
			        	}
			        }
			        $entranceCoef=count($entranceCoef);
		        	$relevance-=($entranceCoef*2);
		    		if(!in_array($subdiv, $subdready))
			        {
			    		$result['subdiv'][$relevance][]=$subdiv;
			    		$subdready[]=$subdiv;
			   		}

			  	}
	    	}
	    }
    continue;
    }
 //------------------------------------------------FIRM-------------------------------------------
 	if($_GET['obj']=='products')
 	{


 //------------------------------------PRODUCTS-----------------------------------//

	$aConnect=new connect('pr');
	$res=$aConnect->select_all($_GET['city'], "WHERE name LIKE '%".$stSearch."%'");// or brend LIKE '%".$stSearch."%' or model LIKE '%".$stSearch."%'");
	while($row=mysql_fetch_array($res))
	{
		//---------------------------prName---------------
		$relevance=getRelevantRes($row['name'], $searchWord, $stSearch);
		$relRes=getRelevance($search, 60, 0, $row['name'], $relevance, 2);
		$relevance=$relRes['searchRelevance'];
		$ec=$relRes['EC'];
        $relevance-=($ec*3);
	    if(!in_array($row['name'], $prNameready))
	    {
			$result['prName'][$relevance][]=$row['id'].'^'.$row['name'].'^'.$row['brend'].'^'.$row['model'].'^'.$row['price'];
		    $prNameready[]=$row['name'];
		}
  	}
//------------------------PrBrend----------------------------------//
    $res=$aConnect->select_all($_GET['city'], "WHERE brend LIKE '%".$stSearch."%'");// or brend LIKE '%".$stSearch."%' or model LIKE '%".$stSearch."%'");
	while($row=mysql_fetch_array($res))
	{
		$relevance;
		$relevance=getRelevantRes($row['brend'], $searchWord, $stSearch);
		$relRes=getRelevance($search, 60, 0, $row['brend'], $relevance, 2);
		$relevance=$relRes['searchRelevance'];
		$ec=$relRes['EC'];
        $relevance-=($ec*3);
	    if(!in_array($row['brend'], $prBrendready))
	    {
			$result['prBrend'][$relevance][]=$row['id'].'^'.$row['name'].'^'.$row['brend'].'^'.$row['model'].'^'.$row['price'];
		    $prBrendready[]=$row['brend'];
		}
    }
  //--------------------------------prModel----------------------------------//
    $res=$aConnect->select_all($_GET['city'], "WHERE model LIKE '%".$stSearch."%'");// or brend LIKE '%".$stSearch."%' or model LIKE '%".$stSearch."%'");
	while($row=mysql_fetch_array($res))
	{
		$relevance;
		$relevance=getRelevantRes($row['model'], $searchWord, $stSearch);
		$relRes=getRelevance($search, 60, 0, $row['model'], $relevance, 2);
		$relevance=$relRes['searchRelevance'];
		$ec=$relRes['EC'];
        $relevance-=($ec*3);
		if(!in_array($row['model'], $prModelready))
	    {
			$result['prModel'][$relevance][]=$row['id'].'^'.$row['name'].'^'.$row['brend'].'^'.$row['model'].'^'.$row['price'];
		    $prModelready[]=$row['model'];
		}
	}
	continue;
	}
}

//include('class/class_connect.php');
include('class/class_page.php');
include('class/city_rus.php');
include('class/class_form.php');
include('class/image_class.php');
session_start();
class searchPage extends page
{
	var $row=array();
	var $cityRus;
	var $searchRes=array();
	function __construct($searchRes=array())
	{
		$this->searchRes=$searchRes;
		$this->cityRus=new city_rus_class();
		parent::__construct();
	}
	function title()
	{
		echo $_GET['search'].' '.$this->cityRus->city_rus_im($_GET['city']);
	}
	function maincontent()
	{		if($_GET['obj']=='firms')$objRus='по компаниям';
		if($_GET['obj']=='products')$objRus='по товарам и услугам';
		if($_GET['obj']=='division')$objRus='по разделам и подразделам';
		if($_GET['obj']=='prName')$objRus='по наименованию';
		if($_GET['obj']=='prBernd')$objRus='по марке';
		if($_GET['obj']=='prModel')$objRus='по бренду';
		echo ('
		<link rel="stylesheet" type="text/css" href="style/search.css" />
		<div class="searchPage">
		<center><h3>Результаты поиска "'.$_GET['search'].'" '.$objRus.'</h3></center>
		');
		$searchRes=array();
		$result=array();
		$result=$this->searchRes;
		$aConnect=new connect('f');
        $shownFirms=array();
        $shownMalls=array();
        if($result['division'])
        {
        	$count=0;
        	for($i=0; $i<60; $i++)
        	{
        		if($result['division'][$i])
        		{
        			$count+=count($result['division'][$i]);
        		}
        	}
        	echo ('
        	<div class="searchob">Разделы</div>
        	<amount>Результатов: '.$count.'</amount>
        	');
        	for($i=0; $i<60; $i++)
        	{
        		if($result['division'][$i])
        		{
        			foreach($result['division'][$i] as $key=>$division)
        			{
        				$divLink=str_replace(' ', '+', $division);
	        			echo ('
	   					<div class="searchResult">
	   						<a href="division.php?city='.$_GET['city'].'&division='.$divLink.'">'.$division.'</a>
	   					</div>
	   					');
   					}
   				}
        	}
        }
        if($result['subdiv'])
        {
        	$count=0;
        	for($i=0; $i<60; $i++)
        	{
        		if($result['subdiv'][$i])
        		{
        			$count+=count($result['subdiv'][$i]);
        		}
        	}
        	echo ('
        	<div class="searchob">Подразделы</div>
        	<amount>Результатов: '.$count.'</amount>
        	');
        	for($i=0; $i<60; $i++)
        	{
        		if($result['subdiv'][$i])
        		{
        			foreach($result['subdiv'][$i] as $key=>$subdiv)
        			{
        				$divLink=str_replace(' ', '+', $subdiv);
	        			echo ('
	   					<div class="searchResult">
	   						<a href="firms_list.php?city='.$_GET['city'].'&subdiv='.$divLink.'">'.$subdiv.'</a>
	   					</div>
	   					');
   					}
   				}
        	}
        }
        if($result['obj'])
        {
        	 $n=0;
        	 $link=false;
        	for($i=0; $i<60; $i++)
        	{

        		if($result['obj'][$i])
        		{

        			foreach($result['obj'][$i] as $key=>$obj)
        			{
        				 $n++;
        				 if($n>11 && $_GET['obj']!='firms')
        				 {
        				 	//echo $link;
        				 	break;
        				 }

        				$resultEls=explode('^', $obj);
        				$obj=$resultEls[0];
        				if($obj=='firms')
						{
							$id=$resultEls[1];
							if(in_array($id, $shownFirms))continue;
							$name=$resultEls[2];
							$short=$resultEls[3];
							$searchRes['Компании'][]='
							<tr>
								<td align="center" class="img">
									<a href="firms.php?city='.$_GET['city'].'&id='.$id.'"><img src="pictures/firmspics/'.$_GET['city'].'/'.$id.'.jpg" height="40" /></a>
								</td>
								<td>
									<div class="searchResult">
										<a class="searchFirmName" href="firms.php?city='.$_GET['city'].'&id='.$id.'">'.$name.'</a><br />'.$short.'
									</div>
								</td>
							</tr>
							';
							$shownFirms[]=$id;

						}
						if($obj=='malls')
						{
							$id=$resultEls[1];
							if(in_array($id, $shownMalls))continue;
							$name=$resultEls[2];
							$short=$resultEls[3];
							$searchRes['Компании'][]='
							<tr>
								<td align="center" class="img">
									<a href="malls.php?city='.$_GET['city'].'&id='.$id.'">
										<img src="pictures/mallspics/'.$_GET['city'].'/'.$id.'.jpg" height="40" />
									</a>
								</td>
								<td>
									<div class="searchResult">
										<a class="searchFirmName" href="malls.php?city='.$_GET['city'].'&id='.$id.'">'.$name.'</a><br />'.$short.'
									</div>
								</td>
							</tr>
							';
							$shownMalls[]=$id;

						}
        			}
        		}
        	}
        	echo (//$link.'
        	'</table>'.$link.'
        	');
        }

       // print_r($result);
		if($result['prName'] or $result['prBrend'] or $result['prModel'])
		{
			echo ('
	        <div class="searchob">Товары и услуги</div>
	        ');
			if(count($result['prName']))
	        {
	        	$shownPrNames=array();
	        	for($i=0; $i<60; $i++)
	        	{
	        		if($result['prName'][$i])
	        		{
	        			foreach($result['prName'][$i] as $key=>$product)
	        			{
	        				$productEls=explode('^', $product);
	        				if(in_array($productEls[1], $shownPrNames))continue;
	        				$shownPrNames[]=$productEls[1];
	        				$nameLink=str_replace(' ', '+', $productEls[1]);
	        				$brendLink=str_replace(' ', '+', $productEls[2]);
	        				$modelLink=str_replace(' ', '+', $productEls[3]);
	        				$searchRes['Наименование'][]=
	        				'<div class="searchResult">
	        					<a href="products.php?product='.$nameLink.'&city='.$_GET['city'].'">'.$productEls[1].'</a>
	        				</div>
	        				';
	        			}
	        		}
	        	}
	        }
	        if(count($result['prBrend']))
	        {
	        	$shownPrBrends=array();
	        	for($i=0; $i<60; $i++)
	        	{
	        		if($result['prBrend'][$i])
	        		{
	        			foreach($result['prBrend'][$i] as $key=>$product)
	        			{
	        				$productEls=explode('^', $product);
	        				if(in_array($productEls[2], $shownPrBrends))continue;
	        				$shownPrBrends[]=$productEls[2];
	        				$nameLink=str_replace(' ', '+', $productEls[1]);
	        				$brendLink=str_replace(' ', '+', $productEls[2]);
	        				$modelLink=str_replace(' ', '+', $productEls[3]);
	        				$searchRes['Марка'][]='
	        				<div class="searchResult">
	        					<a href="products.php?product='.$brendLink.'&city='.$_GET['city'].'">'.$productEls[2].'</a>
	        				</div>
	        				';
	        			}
	        		}
	        	}
	        }
	        if(count($result['prModel']))
	        {
	        	$shownPrModels=array();
	        	for($i=0; $i<59; $i++)
	        	{
	        		if($result['prModel'][$i])
	        		{
	        			foreach($result['prModel'][$i] as $key=>$product)
	        			{
	        				$productEls=explode('^', $product);
	        				if(in_array($productEls[3], $shownPrModels))continue;
	        				$shownPrModels[]=$productEls[3];
	        				$nameLink=str_replace(' ', '+', $productEls[1]);
	        				$brendLink=str_replace(' ', '+', $productEls[2]);
	        				$modelLink=str_replace(' ', '+', $productEls[3]);
	        				$searchRes['Модель'][]='
	        				<div class="searchResult">
	        				<a href="products.php?product='.$brendLink.'&city='.$_GET['city'].'">'.$productEls[2].'</a>
	        				<a href="products.php?product='.$modelLink.'&city='.$_GET['city'].'">'.$productEls[3].'</a>
	        				</div>
	        				';
	        			}
	        		}
	        	}
	        }
        }
        $count=0;
         foreach($searchRes as $obj=>$res)
        {        	for($i=0; $i<count($res); $i++)
        		$count++;
        }

        if($_GET['obj']!='division')$page=new pagin($searchRes, $count);
        //print_r($searchRes);

        echo ('
        </div>
        ');
	}
}
class pagin extends paginator
        {
        	var $searchRes;
        	var $count;
        	function __construct($searchRes=array(), $count)
        	{
        		$this->searchRes=$searchRes;
        		$this->count=$count;
        		parent::__construct(10);
        	}
        	function countRows()
        	{
        		return $this->count;
        	}
        	function pageContent()
        	{
            	 foreach($this->searchRes as $obj=>$res)
		        {
		        	echo ('
		        	<center><h4>
		        		'.$obj.'
		    		</h4></center>
		    		');
		        	for($i=$this->lim; $i<($this->limit+$this->lim); $i++)
		        	{		        		if($obj=='Компании')
		        		echo '<table>';
		        		echo $res[$i];
		        		echo '</table>';
                     }
		        }
        	}
        }
$anAddFirms=new searchPage($result);
